package com.example.paging.ui

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.paging.R
import com.example.paging.entity.HomeVO

class ArticleAdapter : PagingDataAdapter<HomeVO.Data.Datas, ArticleAdapter.ArticleViewHolder>(
    POST_COMPARATOR
) {

    companion object {
        val POST_COMPARATOR = object : DiffUtil.ItemCallback<HomeVO.Data.Datas>() {
            override fun areItemsTheSame(
                oldItem: HomeVO.Data.Datas,
                newItem: HomeVO.Data.Datas
            ) =
                oldItem == newItem


            override fun areContentsTheSame(
                oldItem: HomeVO.Data.Datas,
                newItem: HomeVO.Data.Datas
            ) =
                oldItem.id == newItem.id


        }
    }

    class ArticleViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val tvName: TextView = view.findViewById(R.id.textview)
    }

    override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) {
        holder.tvName.text = getItem(position)?.title
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder {
        val viewHolder = ArticleViewHolder(LayoutInflater.from(parent.context)
            .inflate(R.layout.item_article, parent, false))
        viewHolder.itemView.setOnClickListener {
            WebActivity.activityStart(parent.context, getItem(viewHolder.absoluteAdapterPosition)!!.link)
        }

        return viewHolder
    }
}